package com.cloudcc.mobile.view.dynamic.dynamic;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager.LayoutParams;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.CApplication;
import com.cloudcc.cloudframe.adapter.CommonPagerAdapter;
import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.bus.MenuToggleEvent;
import com.cloudcc.cloudframe.model.param.DynamicType;
import com.cloudcc.cloudframe.ui.viewgroup.CustomViewpager;
import com.cloudcc.cloudframe.util.NearByUtil;
import com.cloudcc.cloudframe.util.SharePreferece;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.ChatIndexAdapter;
import com.cloudcc.mobile.entity.MyChatter;
import com.cloudcc.mobile.event.refresh.RefreshDynamicListEvent;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.view.base.BaseTabFragment;
import com.cloudcc.mobile.view.dynamic.SendTimeLineActivity;
import com.litesuits.android.log.Log;
import com.mypage.utils.NetStateUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 主页 （tab）
 * 
 * @author wangzhiqiang
 * @date 2015-6-24 上午9:25:45 协作
 */
public class DynamicMainFragment extends BaseTabFragment implements IEventLife {

	@Bind(R.id.textView1)
	TextView title;

	@Bind(R.id.indexselect)
	RelativeLayout indexselect;// 上面的选择框

	@Bind(R.id.viewpager)
	CustomViewpager mViewPager;
	@Bind(R.id.titlebar)
	RelativeLayout titlebar_h;
	@Bind(R.id.imageView3)
	ImageView mimageView3;
    @Bind(R.id.message_num_tz)
    TextView message_num_tz;
	@Bind(R.id.message_num_99d)
	TextView message_num_99d;


	private PopupWindow dynamicTypePopu;// 弹出的动态类型选择狂

	private ChatIndexAdapter adapter;
	private List<MyChatter> total = new ArrayList<MyChatter>();

	private IndexReceiver receiver;
	// 加载更多的
	private int skip = 0, page = 1, count = 0;
	private MyChatter myChatter;
	private String weizhiid;
	private int weizhi;
	private boolean isfavorited;
	int praisenum;
	boolean ispraised;
	public int notifyNum;
	private static String path = Tools.getImagePath("/CloudCC/FuJian/");

	private List<DynamicType> titles;
	private DynamicType currentType;

	private void setCurrentItem(String markOrText) {
		Log.d("tiaozhuan", "tiaozhuandao1");
		for (DynamicType item : titles) {
			String tag = item.tag;
			String text = item.title;
			if (StringUtils.equals(tag, markOrText)
					|| StringUtils.equals(text, markOrText)) {
				currentType = item;
				break;
			}
		}
	}


	@OnClick(R.id.ctrl_menu)
	public void clickMenu() {
		EventEngine.post(new MenuToggleEvent(false, false));
	}

	public ImageView button;

	private void setupView() {
		button = (ImageView) findViewById(R.id.allmenubtn);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				EventEngine.post(new MenuToggleEvent(false, false));
			}
		});
		initPages();
		initTitle();
		receiver = new IndexReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(AppContext.INDEXADAPTER_SHUAXIN);
		getActivity().registerReceiver(receiver, filter);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (!NetStateUtils.isNetworkConnected(getActivity())){
			Toast.makeText(getActivity(),R.string.zanwus,Toast.LENGTH_SHORT).show();
		}
		MessageSetNCL();
		EventEngine.post(new RefreshDynamicListEvent());
//		initTitle();
	}
	private void initPages() {
		List<Fragment> pages = new ArrayList<Fragment>();
		pages.add(new DynamicFollowFragment());
		pages.add(new DynamicMeFragment());
		pages.add(new DynamicMarkFragment());
		pages.add(new DynamicCompanyFragment());
		pages.add(new DynamicAiteFragment());
		mViewPager.setAdapter(new CommonPagerAdapter(getActivity()
				.getSupportFragmentManager(), pages));
	}

	@OnClick(R.id.new_xj)
	public void clickNew() {
		Log.d("newxinde", "点击了右边发微贴");
		Intent intent = new Intent(getActivity(), SendTimeLineActivity.class);
		getActivity().startActivity(intent);
	}

	@OnClick(R.id.indexselect)
	public void clickShowWindow() {
		NearByUtil.startPropertyAnim(mimageView3);
		showWindow();

	}

	private void dismissWindow() {
		if (dynamicTypePopu != null) {

			dynamicTypePopu.dismiss();
			dynamicTypePopu = null;
		}
	}


	private void showWindow() {
		dismissWindow();
		RadioGroup group = (RadioGroup) LayoutInflater.from(getActivity())
				.inflate(R.layout.dynamic_pop, null);
		WindowManager wm = getActivity().getWindowManager();
//		int width = wm.getDefaultDisplay().getWidth();
//		int hight = wm.getDefaultDisplay().getHeight()-titlebar_h.getHeight()-getResources().getDimensionPixelSize(getResources().getIdentifier("status_bar_height", "dimen", "android"));
		dynamicTypePopu = new PopupWindow(group, LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
		dynamicTypePopu.setFocusable(true);
		dynamicTypePopu.setOutsideTouchable(true);
		dynamicTypePopu.setBackgroundDrawable(new ColorDrawable(
				Color.TRANSPARENT));
		int xPos = indexselect.getWidth() / 2 - dynamicTypePopu.getWidth() / 2;
		dynamicTypePopu.showAsDropDown(titlebar_h);
		dynamicTypePopu.setOnDismissListener(new PopupWindow.OnDismissListener() {
			@Override
			public void onDismiss() {
				NearByUtil.startPropertyAnim2(mimageView3);
			}
		});
		String type = currentType.tag;
		android.util.Log.i("yayayaya", "aaaaaaaaaaaaaaaaaaaaaaa"+type);
		group.check(StringUtils.equals(type, RunTimeManager.DynamicType.FOLLOW) ? R.id.dy_follew
				  : StringUtils.equals(type, RunTimeManager.DynamicType.ME) ? R.id.dy_me
			      : StringUtils.equals(type, RunTimeManager.DynamicType.MARK) ? R.id.dy_mark
				  : StringUtils.equals(type, RunTimeManager.DynamicType.MYAT) ? R.id.dy_aiteyou
				  : StringUtils.equals(type, RunTimeManager.DynamicType.COMPANY) ? R.id.dy_company:	R.id.dy_aiteyou
				  );
		group.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup arg0, int checkId) {
				// 增加一个我@出去的帖子
				int currentItem = mViewPager.getCurrentItem();
				if ((currentItem == 0 && checkId == R.id.dy_follew)
						|| (currentItem == 1 && checkId == R.id.dy_me)
						|| (currentItem == 2 && checkId == R.id.dy_mark)
						|| (currentItem == 3 && checkId == R.id.dy_company)
						|| (currentItem == 4 && checkId == R.id.dy_aiteyou)) {
					dismissWindow();
					return;
				}

				switch (checkId) {
				case R.id.dy_follew:
					setCurrentItem(getString(R.string.dynamic_follew));
					break;
				case R.id.dy_me:
					setCurrentItem(getString(R.string.dynamic_me));
					break;
				case R.id.dy_mark:
					setCurrentItem(getString(R.string.dynamic_mark));
					break;
				case R.id.dy_company:
					setCurrentItem(getString(R.string.dynamic_company));
					break;
				case R.id.dy_aiteyou:
//					Toast.makeText(mContext, "点击了@我的陨铁", 1).show();
					setCurrentItem(getString(R.string.dy_aiteyou));
					// setCurrentItem(getString(R.string.dynamic_company));
					break;
					case R.id.dy_huibg:
						dynamicTypePopu.dismiss();
						break;
				}

				title.setText(currentType.title);
				dismissWindow();

			}
		});
	}
	@OnClick(R.id.topbar_right)
	public void onClickRight(){
		EventEngine.post(new MenuToggleEvent(false, true));
	}
	// 标题选择
	private void initTitle() {
		titles = new ArrayList<DynamicType>();
		titles.add(new DynamicType(0, RunTimeManager.DynamicType.FOLLOW,
				getString(R.string.dynamic_follew)));
		titles.add(new DynamicType(1, RunTimeManager.DynamicType.ME,
				getString(R.string.dynamic_me)));
		titles.add(new DynamicType(2, RunTimeManager.DynamicType.MARK,
				getString(R.string.dynamic_mark)));
		titles.add(new DynamicType(3, RunTimeManager.DynamicType.COMPANY,
				getString(R.string.dynamic_company)));
		titles.add(new DynamicType(4, RunTimeManager.DynamicType.MYAT,
				getString(R.string.dy_aiteyou)));
		title.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
			}

			@Override
			public void afterTextChanged(Editable arg0) {
				mViewPager.setCurrentItem(currentType.page, false);
				RunTimeManager.getInstance().setDynamicType(currentType.tag);
			}
		});
		String type = RunTimeManager.getInstance().getDynamicType();
		setCurrentItem("follow");
		title.setText(currentType.title);
	}

	class IndexReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			try {
				String action = intent.getAction();
				if (action.equals(AppContext.INDEXADAPTER_LIUYAN)) {
					//
				} else if (action.equals(AppContext.INDEXADAPTER_XIHUAN)) {
					// 喜欢
					total.get(AppContext.isclieck).setIspraised(
							AppContext.islike);
					adapter.changeData(total);

				} else if (action.equals(AppContext.INDEXADAPTER_SHOUCANG)) {
					total.get(AppContext.isclieck).setIsfavorited(
							AppContext.isshoucang);
					adapter.changeData(total);

				} else if (action.equals(AppContext.INDEXADAPTER_SHANCHU)) {
					// 删除 移除那条记录
					total.remove(AppContext.isclieck);
					adapter.changeData(total);
				} else if (action.equals(AppContext.INDEXADAPTER_SHUAXIN)) {
					// onRefreshData();
				}
			} catch (Exception e) {
				Tools.handle(e);
			}
		}
	}

	class Ddialog {
		private TextView name;
		private Button cancle, sure;
	}

	public void saveChatQueryType(String name) {
		SharePreferece share = new SharePreferece(mContext);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("ChatQueryType", name);
		Log.d("save", name + "保存到数据库中");
		share.SaveShare(
				UserManager.getManager().getUser().userId + "QueryType", map);
	}

	@Override
	public void init() {
		setupView();
	}

	@Override
	public int getLayoutId() {
		return R.layout.chat_index2;
	}

	@Override
	public void register() {
		EventEngine.register(this);
	}

	@Override
	public void unRegister() {
		EventEngine.uregister(this);
	}

	@Override
	public void onDestroy() {
		try {
			getActivity().unregisterReceiver(receiver);
		} catch (Exception e) {
			Tools.handle(e);
		}
		super.onDestroy();
	}
//	public long messagenum;
public void MessageSetNCL(){
	long messagenum = 0;
	messagenum= RunTimeManager.getInstance().getMessageNx();
    message_num_tz.setText(messagenum+"");
	if(messagenum>0) {
		message_num_tz.setVisibility(View.VISIBLE);
		if(messagenum>99) {
			message_num_tz.setVisibility(View.INVISIBLE);
			message_num_99d.setVisibility(View.VISIBLE);
		}

	}else {
		message_num_tz.setVisibility(View.INVISIBLE);
		message_num_99d.setVisibility(View.INVISIBLE);
	}

}
}

